import { createRouter, createWebHistory } from "vue-router";
import storage from "../storage/storage";
const routes = [
  {
    path: "/",
    name: "login",
    component: () => import("@/view/login.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () => import("@/view/register.vue"),
  },
  {
    path: "/index",
    name: "index",
    component: () => import("@/view/index.vue"),
    redirect: "/home/homePage",
    children: [
      {
        path: "/home/homePage",
        name: "homePage",
        component: () => import("@/view/home/homePage.vue"),
      },
      {
        path: "/home/perCenter",
        name: "perCenter",
        component: () => import("@/view/home/perCenter.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  //如果没登陆过去登录
  console.log(storage.getCookies("session"));
  if (!storage.getCookies("session")) {
    if (to.name == "register") {
      next();
    } else if (to.name != "login") {
      next({ path: "/" });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
